﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.BussLogic;
using TimKen.DataEntity;
using System.Data;
using System.Data.SqlClient;
using GemBox.Spreadsheet;
using System.IO;
using System.Collections;


namespace TimKen.Web.Admin.Product
{
    public partial class Product_List : TimKen.App.AdminPage
    {
        private PCategoryManager categoryManager = new PCategoryManager();
        private ProductManager productManager = new ProductManager();
        private POptionManager optionManager = new POptionManager();
        private PAttributeManager attributeManager = new PAttributeManager();

        private string toadd = "├";


        public override string ActionCode
        {
            get
            {
                return "88";
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //绑定产品分类
                this.ddlCategory.Items.Clear();
                this.ddlCategory.Items.Add(new ListItem(GetLangString("ChooseCategory"), "-1"));
                this.ddlCategory.Items.Add(new ListItem(GetLangString("SetAsRootCategory"), "0"));

                //绑定品牌列表
                BindBrandList();
                BindProductCategory("0");
                BindResources();
                BindData();
            }

            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.btnDownLoadTemplate);
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.btnUploadProduct);

            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.btnDownLoadTemplate2);
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.btnUploadProduct2);
        }

        /// <summary>
        ///  绑定属性列表数据
        /// </summary>
        protected void BindData()
        {
            int categoryId = int.Parse(this.ddlCategory.SelectedValue);
            int brandId = int.Parse(this.ddlBrand.SelectedValue);
            string keyWords = this.txtKeywords.Text.Trim();
            bool showFreezen = chkShowFreeze.Checked;

            DataSet ds = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, brandId, categoryId, keyWords, "", showFreezen, false,0);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0]["total"]);

            this.grdProduct.DataSource = ds;
            this.grdProduct.DataBind();
        }

        public void BindResources()
        {

            btnSearch.Text = GetLangString("Search");
            chkShowFreeze.Text = GetLangString("ShowFreezen");
            btnDownLoadTemplate.Text = GetLangString("DownLoadTemplate");
            btnUploadProduct.Text = GetLangString("UploadProduct");

            btnDownLoadTemplate2.Text = GetLangString("DownLoadTemplate");
            btnUploadProduct2.Text = GetLangString("UploadProduct");
            this.AspNetPager1.SubmitButtonText = GetLangString("Go");
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }



        /// <summary>
        /// 绑定产品分类分级选择列表
        /// </summary>
        private void BindProductCategory(string parentId)
        {
            DataSet ds = categoryManager.GetList(LanguageWhereStr + " AND ParentID=" + parentId);
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    this.ddlCategory.Items.Add(new ListItem(toadd + " " + dr["CategoryName"].ToString(), dr["CategoryID"].ToString()));
                    toadd += "─┴";
                    BindProductCategory(dr["CategoryID"].ToString());
                    toadd = toadd.Substring(0, toadd.Length - 2);
                }
            }
        }


        private void BindBrandList()
        {
            string sql = "SELECT  BrandID,Name FROM PBrand";
            SqlDataReader reader = DataAccess.DbHelperSQL.ExecuteReader(sql);
            this.ddlBrand.Items.Add(new ListItem(GetLangString("ChooseBrand"), "0"));

            while (reader.Read())
            {
                this.ddlBrand.Items.Add(new ListItem(reader["Name"].ToString(), reader["BrandID"].ToString()));
            }

            reader.Close();
            reader.Dispose();
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void ddlBrand_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void grdProduct_Sorted(object sender, EventArgs e)
        {
            SortDirection SortDirection = this.grdProduct.SortDirection;
            string field = this.grdProduct.SortExpression;
        }

        protected void chkShowFreeze_CheckedChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnDownLoadTemplate_Click(object sender, EventArgs e)
        {
            DownLoadTemplateFile("importtemplet.xls");
        }

        protected void btnDownLoadTemplate2_Click(object sender, EventArgs e)
        {
            DownLoadTemplateFile("importtemplet2.xls");
        }


        protected void DownLoadTemplateFile(string filename)
        {
            try
            {
                string path = UploadFilePathForProduct + filename;


                if (System.IO.File.Exists(Server.MapPath(path)))
                {

                    string filePath = Server.MapPath(path);//路径 

                    //以字符流的形式下载文件 
                    FileStream fs = new FileStream(filePath, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开 
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    Alert(GetLangString("NotFoundFile"));
                }
            }
            catch
            {
                Response.Redirect("/Error.aspx");
            }

        }

        protected void btnUploadProduct_Click(object sender, EventArgs e)
        {
            #region  上传Excel数据文件
            string fileName = "";
            try
            {
                if (this.FileUpload1.FileBytes.Length == 0)
                {
                    Alert("文件为空");
                }

                bool fileOK = false;
                fileName = System.DateTime.Now.ToString("yyyyMMddhhmmss") + this.FileUpload1.FileName;
                if (this.FileUpload1.HasFile)
                {
                    string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

                    string[] allowedExtensions = { ".xls", ".xlsx" };

                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }
                if (fileOK)
                {
                    try
                    {
                        this.FileUpload1.SaveAs(PhysicalUploadFilePathForProduct + fileName);
                    }
                    catch
                    {
                        Alert(GetLangString("UploadFailure"));
                    }
                    finally
                    {
                    }
                }

                else
                {
                    Alert(GetLangString("UploadFailure"));
                }
            }
            catch
            {
                Alert(GetLangString("UploadFailure"));
            }

            #endregion



            #region 解释Excel文件导入

            try
            {
                ExcelFile ef = new ExcelFile();

                ef.LoadXls(PhysicalUploadFilePathForProduct + fileName, XlsOptions.None);

                foreach (ExcelWorksheet sheet in ef.Worksheets)
                {

                    Hashtable ht = new Hashtable();
                    //扩展属性
                    for (int i = 4; i < sheet.Rows[0].AllocatedCells.Count; i++)
                    {
                        if (sheet.Rows[0].Cells[i].Value == null || string.IsNullOrEmpty(sheet.Rows[0].Cells[i].Value.ToString().Trim()))
                            break;

                        int optionId = optionManager.GetPOptionID(sheet.Rows[0].Cells[i].Value.ToString().Trim());

                        if (optionId != 0)
                            ht.Add(optionId, i);
                    }
                    Cache.Insert("OptionIndex", ht, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);

                    for (int row = 2; row < sheet.Rows.Count; row++)
                    {
                        if (sheet.Rows[row].Cells[0].Value == null)
                            continue;

                        string ItemCode = sheet.Rows[row].Cells[0].Value.ToString();
                        string CategoryName = sheet.Rows[row].Cells[1].Value.ToString();
                        string BrandName = sheet.Rows[row].Cells[2].Value.ToString();


                        string IntroDocFiles = sheet.Rows[row].Cells[3].Value == null ? "" : sheet.Rows[row].Cells[3].Value.ToString();


                        //更新产品信息
                        DataEntity.Product product = productManager.GetModel(ItemCode.Trim());
                        if (product == null)
                            continue;
                        if (GetCategoryID(CategoryName) != 0)
                        {
                            product.CategoryID = GetCategoryID(CategoryName);
                        }
                        product.BrandID = GetBrandID(BrandName.Trim());
                        product.IntroDocFiles = IntroDocFiles;

                        productManager.Update(product);

                        Hashtable htIndex = GetIndexsByCategoryID(product.CategoryID.Value);

                        foreach (System.Collections.DictionaryEntry de in htIndex)
                        {
                            if (de.Value == null)
                                continue;

                            if (sheet.Rows[row].Cells[int.Parse(de.Value.ToString())].Value == null)
                                continue;

                            string values = sheet.Rows[row].Cells[int.Parse(de.Value.ToString())].Value.ToString();
                            int optionId = int.Parse(de.Key.ToString());

                            if (values.Trim() == "")
                                continue;


                            //清空属性值 miaozy  at 090603 
                            if (values.ToLower().Trim() == "null")
                            {
                                attributeManager.Delete(product.ProductID, optionId);
                                continue;

                            }


                            //更新产品属性的中英文值,如果有分号(中文;英文),则全部更新,否则两个值一样
                            DataEntity.PAttribute attributeCn = new TimKen.DataEntity.PAttribute();
                            attributeCn.LanguageID = (int)LanguageEnum.Chinese;
                            attributeCn.OptionID = optionId;
                            attributeCn.OptionValue = values.Contains(";") ? values.Split(';')[0] : values;
                            attributeCn.ProductID = product.ProductID;


                            DataEntity.PAttribute attributeEn = new TimKen.DataEntity.PAttribute();
                            attributeEn.LanguageID = (int)LanguageEnum.English;
                            attributeEn.OptionID = optionId;
                            attributeEn.OptionValue = values.Contains(";") ? values.Split(';')[1] : values;
                            attributeEn.ProductID = product.ProductID;

                            attributeManager.Add(attributeEn);
                            attributeManager.Add(attributeCn);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                Alert(GetLangString("UploadFailure"));
            }
            finally
            {
                FileInfo fi = new FileInfo(PhysicalUploadFilePathForProduct + fileName);
                fi.Delete();
            }
            #endregion
        }

        public Hashtable GetIndexsByCategoryID(int categoryID)
        {
            if (Cache.Get("OptionIndex") == null)
                throw new Exception("Error");

            Hashtable ht = Cache.Get("OptionIndex") as Hashtable;


            Hashtable htr = new Hashtable();
            object cg = Cache.Get("CategoryOptionIndex" + categoryID);
            if (cg == null)
            {
                DataSet ds = categoryManager.GetOptionByCategory(categoryID.ToString());
                foreach (DataRow dr in ds.Tables[0].Select("LanguageID=2"))
                {
                    htr.Add(dr["OptionID"], ht[int.Parse(dr["OptionID"].ToString())]);
                }
            }
            else
            {
                htr = cg as Hashtable;
            }

            return htr;
        }

        /// <summary>
        /// 处理冻结产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUploadProduct2_Click(object sender, EventArgs e)
        {
            #region  上传Excel数据文件
            string fileName = "";
            try
            {
                if (this.FileUpload2.FileBytes.Length == 0)
                {
                    Alert("文件为空");
                }

                bool fileOK = false;
                fileName = System.DateTime.Now.ToString("yyyyMMddhhmmss") + this.FileUpload2.FileName;
                if (this.FileUpload2.HasFile)
                {
                    string fileExtension = System.IO.Path.GetExtension(FileUpload2.FileName).ToLower();

                    string[] allowedExtensions = { ".xls", ".xlsx" };

                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }
                if (fileOK)
                {
                    try
                    {
                        this.FileUpload2.SaveAs(PhysicalUploadFilePathForProduct + fileName);
                    }
                    catch (Exception ex)
                    {
                        //TimKen.App.Clogs.LogError("Uploading", ex);
                        PageAlert("Uploading:" + ex.ToString());
                        //Alert(GetLangString("UploadFailure"));
                    }
                    finally
                    {
                    }
                }
                else
                {
                    Alert("上传格式不正确！");
                    //Alert(GetLangString("UploadFailure"));
                }
            }
            catch (Exception x)
            {
                TimKen.App.Clogs.LogError("Upload", x);
                PageAlert("Upload:" + x.ToString());
                //Alert(GetLangString("UploadFailure"));
            }

            #endregion

            try
            {
                ExcelFile ef = new ExcelFile();

                ef.LoadXls(PhysicalUploadFilePathForProduct + fileName, XlsOptions.None);

                foreach (ExcelWorksheet sheet in ef.Worksheets)
                {

                    for (int row = 2; row < sheet.Rows.Count; row++)
                    {
                        if (sheet.Rows[row].Cells[0].Value == null)
                            continue;

                        string ItemCode = sheet.Rows[row].Cells[0].Value.ToString();

                        bool isDisplay = false;
                        if (sheet.Rows[row].Cells[1].Value.ToString().Trim() == "1")
                            isDisplay = true;

                        //更新产品信息
                        DataEntity.Product product = productManager.GetModel(ItemCode.Trim());
                        if (product == null)
                            continue;

                        product.IsDisplay = isDisplay;

                        productManager.Update(product);

                        BindData();
                    }
                }
            }
            catch (Exception ee)
            {
                TimKen.App.Clogs.LogError("提交订单出错", ee);
                PageAlert("Update:" + ee.ToString());
                //Alert(GetLangString("UploadFailure"));
            }
            finally
            {
                FileInfo fi = new FileInfo(PhysicalUploadFilePathForProduct + fileName);
                fi.Delete();
            }
        }
        /// <summary>
        /// 输出简单信息
        /// </summary>
        /// <param name="strInfo">错误描述</param>
        public void PageAlert(string strInfo)
        {
            string strMsg = strInfo.Replace("\r\n", ",");
            Response.Write("<script>window.alert('" + strMsg + "')</script>");
        }
    }
}
